const multer=require("multer");
const path=require("path");

module.exports = function (options={field:'file',replace:null,share:false}) {

    const storage = multer.diskStorage({
        destination: (req, file, callback) => {
          callback(null, 'public/upload/');
        },
        filename: (req, file, callback) => {
          let extname=path.extname(file.originalname);         
          callback(null,file.fieldname+"-"+Date.now()+extname);
        },
    });
    const upload = multer({ storage }).single(options.field);  
    
    return function (req, res, next) {       
        upload(req, res, error => {
           
            if (error) {        
                console.error(error);        
                res.status(500).json({ status: 'fail', response: { err: '上传失败'} });
            } else {
                const imageUrl = `/upload/${req.file.filename}`; 
                console.log('上传:'+ imageUrl) 
                if(options.share){
                    if(options.replace){
                        req.body[options.replace]=imageUrl;
                    }else  req.body[options.field]=imageUrl;
                    next();                   
                }else{
                    res.json({ status: 'success', response: { url: imageUrl} });
                } 
            }
        });
    }
}